<template>
    <div class="app-container">
        <div class="filter-container">
            <!-- 下拉选择学期 -->
            <el-select class="filter-item semester-select" v-model="semesterId" placeholder="请选择学期"
                @change="changeSemester">
                <el-option v-for="(item, index) in semesterData" :key="index" :value="item.id"
                    :label="item.semesterName"></el-option>
            </el-select>
            <!-- 下拉选择教室 -->
            <el-select class="filter-item room-select" @change="handleSelectChange" @clear="clearListener" clearable
                v-model="roomNo" placeholder="请选择教室">
                <el-option v-for="(item, index) in roomData" :key="index" :value="item.roomNo"
                    :label="item.roomName"></el-option>
            </el-select>
            <el-button class="filter-item" type="primary" @click="exportExcel">导出课表</el-button>
        </div>
        <br />
        <el-table :data="classTableData.lessons" border style="width: 100%" id="my-table">
            <!-- 时间列 -->
            <el-table-column prop="name" label="时间" width="180">
                <template #default="scope">
                    <p>{{ "第" + digital2Chinese(scope.$index + 1) + "节" }}</p>
                    <p class="period">{{ scope.row }}</p>
                </template>
            </el-table-column>

            <!-- 周次和课程信息列 -->
            <el-table-column v-for="(weekNum, weekIndex) in classTableData.courses" :key="weekIndex"
                :label="'周' + digital2Chinese(weekIndex + 1, 'week')" width="180">
                <template #default="scope">
                    <div class="course-info" v-html="classTableData.courses[weekIndex][scope.$index]"></div>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
import { ElMessage } from 'element-plus';
import axios from 'axios'; // 假设您会配置axios实例或直接使用

const classTimeTableData = ref([]);
const roomData = ref([]);
const semesterData = ref([]);
const roomNo = ref("");
const semesterId = ref("");
const listLoading = ref(true);

const classTableData = ref({
    lessons: [
        "08.20-09.55",
        "10.15-11.50",
        "14.20-15.55",
        "16.15-17.50",
        "18.30-20.05",
    ],
    courses: [[], [], [], [], [], [], []],
    timetableId: [[], [], [], [], [], [], []],
    timeslot: [[], [], [], [], [], [], []],
});

const changeSemester = () => {
    clearListener();
    // 根据需求，学期改变后，如果教室已选，则查询，否则清空或重新获取列表
    if (roomNo.value) {
        queryClassTableByRoom();
    } else {
        // 如果希望清空课表，则调用 initClassTableData()
        // 如果希望获取该学期下所有教室的课表总览（如果getList支持学期参数），则调整getList
        getList(); // 当前是获取所有课表
    }
};

const initClassTableData = () => {
    classTableData.value = {
        lessons: [
            "08.20-09.55",
            "10.15-11.50",
            "14.20-15.55",
            "16.15-17.50",
            "18.30-20.05",
        ],
        courses: [[], [], [], [], [], [], []],
        timetableId: [[], [], [], [], [], [], []],
        timeslot: [[], [], [], [], [], [], []],
    };
    return true;
};

const setToTable = (ret) => {
    if (!initClassTableData()) {
        return;
    }

    let level = 0;
    let index = 0;
    let beforeTimeslot = -1;
    let flag = false;

    if (roomNo.value === "") {
        flag = true;
    }
    if (semesterId.value === null || semesterId.value === '') {
        flag = true;
    }

    for (let timess = 0; timess < 35; timess++) {
        const item = ret[index];
        if (!flag && item !== undefined && beforeTimeslot === item.timeslot) {
            timess--;
        }
        level = Math.floor(timess / 5);
        if (flag || index >= ret.length || item === undefined || parseInt(item.timeslot) !== timess) {
            classTableData.value.courses[level].push("");
            classTableData.value.timetableId[level].push(-1);
            classTableData.value.timeslot[level].push(timess);
            // 当item不匹配时，不应该 index--，除非ret是严格按timeslot排序且无间隙的
            // 保持 index 不变，让外层循环 timess++ 来跳过这个时间片
        } else {
            let section =
                "(" +
                ((item.timeslot % 5) * 2 + 1) +
                "-" +
                ((item.timeslot % 5) * 2 + 2) +
                "节)";
            let biweekly =
                item.biweekly == 1 ? "(单)" : item.biweekly == 2 ? "(双)" : "";
            let time =
                section + item.startWeek + "-" + item.endWeek + "周" + biweekly;
            let className = item.className;
            let teacherName = item.teacherName;
            let course = item.courseNo + "-" + item.courseName;
            let size = item.size;

            let msg =
                time +
                "/" +
                className +
                "/" +
                teacherName +
                "/" +
                course +
                "/" +
                "选课人数：" +
                size;

            if (beforeTimeslot !== item.timeslot) {
                classTableData.value.courses[level].push(msg);
                if (!classTableData.value.timetableId[level]) classTableData.value.timetableId[level] = [];
                classTableData.value.timetableId[level][item.timeslot % 5] = item.id;
                classTableData.value.timeslot[level].push(item.timeslot);
            } else {
                let oldmsg = classTableData.value.courses[level][item.timeslot % 5];
                classTableData.value.courses[level][item.timeslot % 5] =
                    oldmsg + "<br/>" + msg;
                let oldid =
                    classTableData.value.timetableId[level][item.timeslot % 5];
                classTableData.value.timetableId[level][item.timeslot % 5] =
                    oldid + "@@@" + item.id;
            }
            beforeTimeslot = item.timeslot;
            index++;
        }
    }

    if (ret.length === 0 && !flag) {
        ElMessage({ message: "暂无课表", type: "success" });
    }
};

const getList = async () => {
    listLoading.value = true;
    initClassTableData(); // 获取列表前先初始化/清空课表
    try {
        const res = await axios.get("/api/timetable/getList", { // 假设 /api 是 vite.config.js 中配置的代理
            headers: {
                token: localStorage.getItem("token"),
            },
        });
        let ret = res.data.data;
        classTimeTableData.value = ret.records || ret; // 兼容 ret 直接是数组或包含 records
        setToTable(classTimeTableData.value);
    } catch (error) {
        ElMessage.error("查询课程表失败");
    } finally {
        listLoading.value = false;
    }
};

const queryClassTableByRoom = async () => {
    if (!semesterId.value || !roomNo.value) {
        ElMessage.warning('请先选择学期和教室');
        initClassTableData();
        return;
    }
    listLoading.value = true;
    initClassTableData();
    try {
        const res = await axios.get(
            // 确保这里的 API 地址是正确的，如果用了 proxy，应该写成 /api/timetable/room/...
            `/api/timetable/room/${semesterId.value}/${roomNo.value}`,{
              headers: {
                "token": localStorage.getItem("token"),
              },
            }
        );
        let ret = res.data.data;
        setToTable(ret);
    } catch (error) {
        ElMessage.error("查询教室课表失败");
    } finally {
        listLoading.value = false;
    }
};

const getRoomNo = async () => {
    listLoading.value = true;
    try {
        const res = await axios.get("/api/room/getList",{
          headers: {
            "token": localStorage.getItem("token"),
          },
        }); // 假设 /api 是 vite.config.js 中配置的代理
        roomData.value = res.data.data;
    } catch (error) {
        ElMessage.error("查询教室列表失败");
    } finally {
        listLoading.value = false;
    }
};

const getSemester = async () => {
    listLoading.value = true;
    try {
        const res = await axios.get("/api/semester/getList",{
          headers: {
            "token": localStorage.getItem("token"),
          },
        }); // 假设 /api 是 vite.config.js 中配置的代理
        semesterData.value = res.data.data;
        // 如果有从 store 获取默认学期 ID 的逻辑，可以在这里添加
        // const storeSemesterId = proxy.$store?.getters?.getSemesterId; 
        // if (storeSemesterId) semesterId.value = storeSemesterId;
        semesterId.value = semesterData.value[0].id;
    } catch (error) {
        ElMessage.error("查询学期列表失败");
    } finally {
        listLoading.value = false;
    }
};

onMounted(() => {
    getList(); // 页面加载时获取所有课表或默认课表
    getRoomNo();
    getSemester();
    // 如果有从 store 获取默认学期 ID 的逻辑，并且希望在 mounted 时设置
    // const idFromStore = proxy.$store?.getters?.getSemesterId; 
    // if (idFromStore) {
    //     semesterId.value = idFromStore;
    //     // 如果设置了学期，可能需要根据逻辑决定是否自动查询课表
    // }
});

const exportExcel = () => {
    const myTableElement = document.getElementById("my-table");
    if (!myTableElement) {
        ElMessage.error("找不到课表元素");
        return;
    }
    const ws = XLSX.utils.table_to_sheet(myTableElement);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

    const defaultColWidth = 20;
    const range = XLSX.utils.decode_range(ws["!ref"]);
    if (!ws["!cols"]) ws["!cols"] = [];
    for (let C = range.s.c; C <= range.e.c; ++C) {
        ws["!cols"][C] = { width: defaultColWidth };
    }

    const defaultRowHeight = 100;
    if (!ws["!rows"]) ws["!rows"] = [];
    ws["!rows"][0] = { hpx: 20 };

    for (
        let R = 1;
        R <= 6 && ws[XLSX.utils.encode_cell({ r: R, c: 0 })];
        ++R
    ) {
        ws["!rows"][R] = { hpx: defaultRowHeight };
    }
    const wbout = XLSX.write(wb, { bookType: "xlsx", type: "array" });
    const blob = new Blob([wbout], { type: "application/octet-stream" });
    FileSaver.saveAs(blob, "教室课表.xlsx"); // 修改导出文件名
};

const digital2Chinese = (num, identifier) => {
    const character = [
        "零", "一", "二", "三", "四", "五", "六",
    ];
    if (identifier === "week") {
        if (num === 0 || num === 7) return "日";
        if (num > 0 && num < 7) return character[num];
        return '';
    }
    return character[num] || '';
};

const clearListener = () => {
    roomNo.value = '';
    initClassTableData(); // 清空教室选择后，清空课表
    // 或者根据需求，获取所有课表 getList();
};

const handleSelectChange = (val) => {
    roomNo.value = val;
    if (val) {
        queryClassTableByRoom();
    } else {
        initClassTableData(); // 如果清空选择，则清空课表
        // 或者 getList(); 获取所有课表
    }
};

</script>

<style scoped>
.app-container {
    padding: 20px;
}

.filter-container {
    display: flex;
    align-items: center;
}

.filter-item {
    margin-right: 10px;
}

.semester-select,
.room-select {
    /* 修改类名以匹配 */
    width: 200px;
}

.filter-item:last-child {
    margin-right: 0;
}

.course-info {
    white-space: pre-wrap;
}
</style>